from flask import Blueprint, request, g
from extensions import db
from models import Performance, Employee, User
from utils import success, error, bad_request, forbidden
from datetime import datetime
from flask_jwt_extended import jwt_required, get_jwt_identity

# 创建绩效管理API蓝图
performance_api = Blueprint('performance_api', __name__, url_prefix='/api/performances')

# 获取绩效记录列表
@performance_api.route('/', methods=['GET'])
def get_performances():
    """获取绩效记录列表"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user:
            return error(code=401, msg='用户不存在').to_response()
        
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        period = request.args.get('period')
        year = request.args.get('year', type=int)  # 添加年份筛选参数
        
        # 构建查询
        query = Performance.query
        
        # 普通员工只能查看自己的绩效记录
        if user.role != 'admin':
            # 查找当前用户对应的员工ID
            employee = Employee.query.filter_by(user_id=current_user_id).first()
            if employee:
                query = query.filter(Performance.employee_id == employee.id)
            else:
                # 如果没有对应的员工记录，返回空结果
                query = query.filter(Performance.employee_id == -1)
        
        # 按评估期间筛选
        if period:
            query = query.filter(Performance.period.contains(period))
        
        # 按年份筛选
        if year:
            query = query.filter(Performance.period.like(f'{year}%'))
        
        # 按创建时间倒序排列
        query = query.order_by(Performance.created_at.desc())
        
        # 分页查询
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        performances = []
        # 为普通员工获取最新的绩效记录（本期绩效）
        latest_performance = None
        if user.role != 'admin':
            employee = Employee.query.filter_by(user_id=current_user_id).first()
            if employee:
                latest_performance = Performance.query.filter(
                    Performance.employee_id == employee.id
                ).order_by(Performance.created_at.desc()).first()
        
        for perf in pagination.items:
            performance_data = {
                'id': perf.id,
                'employee_id': perf.employee_id,
                'employee_name': perf.employee.name if perf.employee else None,
                'department_name': perf.employee.department.name if perf.employee and perf.employee.department else None,
                'period': perf.period,
                'score': perf.score,
                'comments': perf.comments,
                'evaluator_id': perf.evaluator_id,
                'evaluator_name': perf.evaluator.name if perf.evaluator else None,
                'created_at': perf.created_at.isoformat(),
                'updated_at': perf.updated_at.isoformat()
            }
            performances.append(performance_data)
        
        # 构建返回数据
        result_data = {
            'performances': performances,
            'pagination': {
                'page': pagination.page,
                'per_page': pagination.per_page,
                'total': pagination.total
            }
        }
        
        # 为普通员工添加本期绩效信息
        if user.role != 'admin' and latest_performance:
            result_data['current_period_performance'] = {
                'period': latest_performance.period,
                'score': latest_performance.score,
                'comments': latest_performance.comments
            }
        
        return success(data=result_data).to_response()
        
    except Exception as e:
        return error(msg=f'获取绩效记录失败: {str(e)}').to_response()

# 创建绩效记录
@performance_api.route('/', methods=['POST'])
def create_performance():
    """创建绩效记录"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user or user.role != 'admin':
            return forbidden(msg='权限不足').to_response()
        
        # 检查请求是否为JSON格式
        if not request.is_json:
            return bad_request('请求必须是JSON格式').to_response()
        
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['employee_id', 'period', 'score']
        for field in required_fields:
            if not data.get(field):
                return bad_request(msg=f'{field}字段不能为空').to_response()
        
        # 验证分数范围
        try:
            score = float(data['score'])
            if score < 0 or score > 100:
                return bad_request(msg='分数必须在0-100之间').to_response()
        except ValueError:
            return bad_request(msg='分数格式错误').to_response()
        
        # 验证员工是否存在
        employee = Employee.query.get(data['employee_id'])
        if not employee:
            return error(code=400, msg='员工不存在').to_response()
        
        # 获取评估者的员工ID
        evaluator = Employee.query.filter_by(user_id=current_user_id).first()
        if not evaluator:
            return error(code=400, msg='评估者信息不存在').to_response()
        
        # 创建绩效记录
        performance = Performance(
            employee_id=data['employee_id'],
            period=data['period'],
            score=score,
            comments=data.get('comments'),
            evaluator_id=evaluator.id
        )
        
        db.session.add(performance)
        db.session.commit()
        
        return success(data={'id': performance.id}, msg='绩效记录创建成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'创建绩效记录失败: {str(e)}').to_response()

# 更新绩效记录
@performance_api.route('/<int:performance_id>', methods=['PUT'])
def update_performance(performance_id):
    """更新绩效记录"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user or user.role != 'admin':
            return forbidden(msg='权限不足').to_response()
        
        performance = Performance.query.get_or_404(performance_id)
        
        # 检查请求是否为JSON格式
        if not request.is_json:
            return bad_request('请求必须是JSON格式').to_response()
        
        data = request.get_json()
        
        # 更新绩效记录
        if 'employee_id' in data:
            # 验证员工是否存在
            employee = Employee.query.get(data['employee_id'])
            if not employee:
                return error(code=400, msg='员工不存在').to_response()
            performance.employee_id = data['employee_id']
        
        if 'period' in data:
            performance.period = data['period']
        
        if 'score' in data:
            try:
                score = float(data['score'])
                if score < 0 or score > 100:
                    return bad_request(msg='分数必须在0-100之间').to_response()
                performance.score = score
            except ValueError:
                return bad_request(msg='分数格式错误').to_response()
        
        if 'comments' in data:
            performance.comments = data['comments']
        
        if 'evaluator_id' in data:
            # 验证评估者是否存在
            evaluator = Employee.query.get(data['evaluator_id'])
            if not evaluator:
                return error(code=400, msg='评估者不存在').to_response()
            performance.evaluator_id = data['evaluator_id']
        
        db.session.commit()
        
        return success(msg='绩效记录更新成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'更新绩效记录失败: {str(e)}').to_response()

# 删除绩效记录
@performance_api.route('/<int:performance_id>', methods=['DELETE'])
def delete_performance(performance_id):
    """删除绩效记录"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user or user.role != 'admin':
            return forbidden(msg='权限不足').to_response()
        
        performance = Performance.query.get_or_404(performance_id)
        
        db.session.delete(performance)
        db.session.commit()
        
        return success(msg='绩效记录删除成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'删除绩效记录失败: {str(e)}').to_response()

# 获取所有员工列表（用于绩效管理页面的员工选择）
@performance_api.route('/employees', methods=['GET'])
def get_all_employees():
    """获取所有员工列表"""
    try:
        employees = Employee.query.all()
        employee_list = []
        
        for emp in employees:
            employee_data = {
                'id': emp.id,
                'name': emp.name,
                'position': emp.position,
                'department_name': emp.department.name if emp.department else None
            }
            employee_list.append(employee_data)
        
        return success(data=employee_list).to_response()
        
    except Exception as e:
        return error(msg=f'获取员工列表失败: {str(e)}').to_response()

# 获取绩效统计信息
@performance_api.route('/statistics', methods=['GET'])
def get_performance_statistics():
    """获取绩效统计信息"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user or user.role != 'admin':
            return forbidden(msg='权限不足').to_response()
        
        # 获取查询参数
        period = request.args.get('period')
        
        # 构建查询
        query = Performance.query
        if period:
            query = query.filter(Performance.period.contains(period))
        
        performances = query.all()
        
        if not performances:
            return success(data={
                'total_count': 0,
                'average_score': 0,
                'score_distribution': {},
                'top_performers': [],
                'low_performers': []
            }).to_response()
        
        # 计算统计数据
        total_count = len(performances)
        total_score = sum(p.score for p in performances)
        average_score = round(total_score / total_count, 2)
        
        # 分数分布
        score_distribution = {
            '优秀(90-100)': len([p for p in performances if 90 <= p.score <= 100]),
            '良好(80-89)': len([p for p in performances if 80 <= p.score <= 89]),
            '中等(70-79)': len([p for p in performances if 70 <= p.score <= 79]),
            '及格(60-69)': len([p for p in performances if 60 <= p.score <= 69]),
            '不及格(0-59)': len([p for p in performances if 0 <= p.score <= 59])
        }
        
        # 按分数排序
        sorted_performances = sorted(performances, key=lambda x: x.score, reverse=True)
        
        # 前5名
        top_performers = []
        for perf in sorted_performances[:5]:
            top_performers.append({
                'employee_name': perf.employee.name if perf.employee else '未知',
                'score': perf.score,
                'period': perf.period
            })
        
        # 后5名
        low_performers = []
        for perf in sorted_performances[-5:]:
            low_performers.append({
                'employee_name': perf.employee.name if perf.employee else '未知',
                'score': perf.score,
                'period': perf.period
            })
        
        statistics = {
            'total_count': total_count,
            'average_score': average_score,
            'score_distribution': score_distribution,
            'top_performers': top_performers,
            'low_performers': low_performers
        }
        
        return success(data=statistics).to_response()
        
    except Exception as e:
        return error(msg=f'获取绩效统计失败: {str(e)}').to_response()

# 获取年度绩效趋势
@performance_api.route('/yearly-trend', methods=['GET'])
@jwt_required()
def get_yearly_trend():
    """获取当前用户的年度绩效趋势数据"""
    try:
        # 获取当前用户
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        
        if not user:
            return error(code=401, msg='用户不存在').to_response()
        
        # 获取员工信息
        employee = Employee.query.filter_by(user_id=current_user_id).first()
        if not employee:
            return error(code=404, msg='员工信息不存在').to_response()
        
        # 获取绩效记录，按评估周期升序排序（从旧到新）
        performances = Performance.query.filter_by(employee_id=employee.id).order_by(Performance.period.asc()).limit(4).all()
        
        # 构建趋势数据
        months = []
        scores = []
        last_performance = 0
        
        for performance in performances:
            months.append(performance.period)
            scores.append(performance.score)
        
        # 获取最新的绩效分数（最后一个）
        if performances:
            last_performance = performances[-1].score
        
        data = {
            "months": months,
            "scores": scores,
            "last_performance": last_performance
        }
        
        return success(data=data).to_response()
        
    except Exception as e:
        return error(msg=f'获取年度绩效趋势失败: {str(e)}').to_response()
